package cn.edt.ctbu.thymeleaf.webapi;

import cn.edt.ctbu.thymeleaf.core.PageUtils;
import cn.edt.ctbu.thymeleaf.domain.Student;
import cn.edt.ctbu.thymeleaf.service.StudentService;
import cn.edt.ctbu.thymeleaf.utils.RUtil;
import cn.edt.ctbu.thymeleaf.vo.R;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/webapi/student")
public class StudentRestController {
    @Autowired
    private StudentService studentService;

    //    读取的url:/webapi/student/list
    @GetMapping("/list")
//    public List<Student> getAll(){
//        List<Student> students=studentService.findAll();
//        return students;
//    }
    public R<Page<Student>> list(int pageIndex,int pageSize){
        Pageable pageable=PageRequest.of(pageIndex,pageSize,Sort.by("id").descending());
        return RUtil.success(studentService.findAll(pageable));
    }
    //        分页读取全部内容
//    sort:排序
    @GetMapping("/getbypage")
    public PageUtils getByPage(
            @RequestParam(value = "page",defaultValue = "0") Integer page,
            @RequestParam(value = "size",defaultValue = "10") Integer size,
            @RequestParam(value = "name",defaultValue = "")String name,
            @RequestParam(value = "no",defaultValue = "")String no,
            @RequestParam(value = "sex",defaultValue = "")Integer sex) {
        //    sort:排序
//        按id倒序
        Sort sort=Sort.by(Sort.Direction.DESC, "id");
        Page<Student> studentPage;
        //判断传入姓名查询
        if(!StringUtils.isEmpty(name)){
            Student student=new Student();
            student.setName(name);
            Pageable pageable=PageRequest.of(0,10,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("name",
                    ExampleMatcher.GenericPropertyMatchers.contains());//全部模糊查询
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        } else if(!StringUtils.isEmpty(no)) {
            Student student=new Student();
            student.setNo(no);
            Pageable pageable=PageRequest.of(0,10,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("no",
                    ExampleMatcher.GenericPropertyMatchers.contains());//全部模糊查询
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }else if(sex != null) {
            Student student=new Student();
            student.setSex(sex);
            Pageable pageable=PageRequest.of(0,10,sort);
            ExampleMatcher matcher=ExampleMatcher.matching().withMatcher("sex",
                    ExampleMatcher.GenericPropertyMatchers.contains());//全部模糊查询
            Example<Student>example=Example.of(student,matcher);
            studentPage=studentService.findAll(example,pageable);
        }
        else{
            Pageable pageable=PageRequest.of(page,size,sort);
            studentPage=studentService.findAll(pageable);
        }
        PageUtils pageUtils=new PageUtils(studentPage.getContent(), studentPage.getTotalElements());
        return pageUtils;

    }

    @PostMapping("/insert")
    public R insert(@Valid Student student, BindingResult bindingResult)
    {
        if (bindingResult.hasErrors()){
            String errorMsg=bindingResult.getFieldError().getDefaultMessage();
            log.info("新增学生出错！{}",errorMsg);
            return RUtil.error(-10,errorMsg);
        }
        student=studentService.insert(student);
        log.info("student id:{}",student.getId());
        return RUtil.success();
    }

    @PutMapping ("/update")
    public Student update(@Valid Student student,BindingResult bindingResult)
    {
        if (bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return null;
        }
        //读取旧数据
        Student oldstudent=studentService.getById(student.getId());
        log.info("student id:{}",student.getId());
        if (StringUtils.isEmpty(student.getPassword())){
            //没有新密码，就用旧密码
            student.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);
        return oldstudent;
    }


    //删除学生/webapi/student/delete
    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id)
    {
        studentService.delete(id);
    }

    //        读取的url:/webapi/student/name,输入姓名查询
    @GetMapping("/name")
    public List<Student> findByName(String name){
        List<Student> students=studentService.findByName(name);
        return students;
    }

    //        读取的url:/webapi/student/no,输入学号查询
    @GetMapping("/no")
    public List<Student> findByNo(String no){
        List<Student> students=studentService.findByNo(no);
        return students;
    }


    //        读取的url:/webapi/student/sex,输入性别查询
    @GetMapping("/sex")
    public List<Student> findBySex(Integer sex){
        List<Student> students=studentService.findBySex(sex);
        return students;
    }

    //按序号查询
    @GetMapping("/id")
    public Student getById(Integer id){
        Student students=studentService.getById(id);
        return students;
    }


    //    读取的url:/webapi/student/get/id
    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id){
        Student student=studentService.getById(id);
        student.setPassword("");
        return student;
    }

//    验证用户名和密码
    @GetMapping("/validateUser")
    public R validateNoAndPassword(String no, String password) throws Exception{
        return RUtil.success(studentService.validateUsernameAndPassword(no,password));
    }

}
